import './public-path';
import { createApp } from 'vue';
import routes from './router/index';
import { createRouter, createWebHistory } from 'vue-router'
import type { Router, RouterHistory } from 'vue-router';
import App from './App.vue';
import {
  renderWithQiankun,
  qiankunWindow,
  QiankunProps,
} from 'vite-plugin-qiankun/dist/helper';
let instance: any = null;
let router: Router|null = null;
let history:  RouterHistory|null = null;
const render = (props: QiankunProps = {}) => {
  const { container } = props
  history = createWebHistory()
  router = createRouter({
    //内部提供了 history 模式的实现。为了简单起见，我们在这里使用 hash 模式。
    history,
    routes,
  })

  //链式运算符识别不了时使用，后面再看看为啥
  // let app:any = null;
  // if(!!container){
  //    app = container.querySelector('#subApp');
  // }else{
  //    app = '#subApp';
  // }
  console.log(container, 999);
  const app = container && container.querySelector('#subApp') || '#subApp'; // 避免 id 重复导致微应用挂载失败
  
  instance = createApp(App)
  instance.use(router)
  instance.mount(app)
  console.log(instance, 23)

  //这种写法获取的不一定是vue实例注意
  // instance = createApp(App).use(router).mount(app)
}
//需要暴露接入协议
const initQianKun = () => {
  renderWithQiankun({
    bootstrap() {
      // console.log('微应用：bootstrap')
    },
    mount(props) { // 获取主应用传入数据
      // console.log('微应用：mount', props)
      render(props)
      //提供一个值，可以被后代组件注入
      instance.provide('pager', props.pager)


      // props.pager.subscribe((v:any)=>{
      //   console.log(v,8888);
      // })
      // props.pager.next({a:'pppp'})
    },
    unmount(props) {
      // console.log('微应用：unmount', props)
      //当前子应用卸载时释放内存，下次又是重新加载
      history = null;
      router = null;
      instance = null;
    },
    update(props) {
      // console.log('微应用：update', props)
    },
  })
} 

console.log(1, qiankunWindow.__POWERED_BY_QIANKUN__);


qiankunWindow.__POWERED_BY_QIANKUN__ ? initQianKun() : render() // 判断是否使用 qiankun ，保证项目可以独立运行
